//
//  YMComposeView.swift
//  YMWeiBo
//
//  Created by mimi on 16/7/28.
//  Copyright © 2016年 mimi. All rights reserved.
//

import UIKit
import pop


class YMComposeView: UIView {
    //记录控制器
    var target:UIViewController?
    //模型数组
    var composeButtonsInfo:[YMComposeButtonInfos] = [YMComposeButtonInfos]()
    //按钮数组
    var buttons:[YMComposeButton] = [YMComposeButton]()

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
  //========================================================
    
    //响应事件
    
    func buttonClick(button:YMComposeButton) {
        
       print(button.composeButtonInfo?.nextvc )
        UIView.animateWithDuration(0.25, animations: { 
            for value in self.buttons{
                
                value.alpha = 0.2
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            
            
            }) { (_) in
                
//                UIView.animateWithDuration(0.25, animations: { 
//                    
//                    
//                    
//                    for value in self.buttons{
//                        value.alpha = 1
//                        value.transform = CGAffineTransformIdentity
//                    }
//                    
//                    }, completion: { (_) in
//                    
//                        guard let vcName = button.composeButtonInfo?.nextvc else{
//                            return
//                        }
//                        
//                        guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
//                            return
//                        }
//                        
//                        print(pn,"=======info")
//                        
//                        guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else{
//                            return
//                        }
//                        //初始化
//                        print(cn,"=======class")
//                        let tempVc = cn.init()
//                        
//                        let navC = UINavigationController(rootViewController: tempVc)
////                        print(vc,"=======info")
//                        self.target?.presentViewController(navC, animated: true, completion: {
//                            
//                            self.removeFromSuperview()
//                        })
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 遍历保存按钮数组
                    for value in self.buttons {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                        
                    }
                    }, completion: { (_) -> Void in
                        guard let vcName = button.composeButtonInfo?.nextvc  else{
                            return
                        }
                        
                        guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                            return
                        }
                        // 判断class 是否为nil 而且是否可以转成UIViewController.Type
                        // 为什么 “SHComposeViewController” 因为OC中根本没有命名空间 erSwift中有命名空间
                        // 如果Swift中获取自定义类的class [项目名.类名]
                        guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else {
                            return
                        }
                        // 初始化
                        let tempVc = cn.init()
                        let navC = UINavigationController(rootViewController: tempVc)
                        self.target?.presentViewController(navC, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
        }
        
        
    }

    
    
    //========================================================
    
    func setupUI(){
        //add控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButton()
        
        //约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        logoImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    
    //字典转模型
    
    func getComposeButtonInfo() ->[YMComposeButtonInfos]{
        let path:String = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let arr = NSArray(contentsOfFile: path)!
        
        var tempArr:[YMComposeButtonInfos] = [YMComposeButtonInfos]()
        
        for dic in arr{
            
            let composeInfo:YMComposeButtonInfos = YMComposeButtonInfos(dic: dic as! [String : AnyObject])
            
            tempArr.append(composeInfo)
            
        }
        return tempArr
    }
    
    //供外界调用的显示View的方法
    
    func composeViewShow(target:UIViewController) {
        self.target = target
        moveButton(true, move: -350)
    }
    
    //点击屏幕button
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        moveButton(false, move: 350)
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
        self.removeFromSuperview()
        }
    }
    

    
    //创建控件button
    func addChildButton() {
        
        composeButtonsInfo = getComposeButtonInfo()
        // 按钮的宽和高
        let childW: CGFloat = 80
        let childH: CGFloat = 110
        // 按钮间距
        let childMargin: CGFloat = (SCREENW - childW*3)/4
        
        for (i,value)in composeButtonsInfo.enumerate() {
            // 得到行数和列数
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            // 创建button
            
            let button = YMComposeButton()
            button.composeButtonInfo = value
            button.addTarget(self, action: #selector(YMComposeView.buttonClick(_:)), forControlEvents: .TouchUpInside)
            
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.frame = CGRect(x: childMargin + (childW+childMargin)*col, y: (childH+childMargin)*row + SCREENH, width: childW, height: childH)


            addSubview(button)
            
            //保存button
            buttons.append(button)
        }
    }
    
    
    func moveButton(isUp:Bool ,move:CGFloat){
        
        let set = isUp ? buttons.enumerate() :  buttons.reverse().enumerate()
        
        for (i,value) in set {
            
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            anim.toValue = NSValue(CGPoint:CGPointMake(value.center.x, value.center.y+move))
            
            anim.beginTime  = CACurrentMediaTime() + Double(i)*0.03
            anim.springBounciness = 10
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
            
        }
        
    }
    
    //        MARK: - 懒加载控件
    
    private lazy var bgImageView:UIImageView = UIImageView(image: UIImage.getScreenShot().applyDarkEffect())
    
    
    
    private lazy var logoImageView:UIImageView = UIImageView(imgName: "compose_slogan")
    
}
